import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pynput.keyboard import Key, Controller as c2
from pynput.mouse import Button, Controller as c1


class vcg_get_cookies:
    def InitialBrowser(self):
        # 驱动器地址
        f = r'/usr/bin/chromedriver'
        # chrome_options 初始化选项
        chrome_options = webdriver.ChromeOptions()
        # 设置浏览器初始 位置x,y & 宽高x,y
        # chrome_options.add_argument(f'--window-position={217},{172}')
        # chrome_options.add_argument(f'--window-size={1200},{1000}')
        # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
        # window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
        # 关闭开发者模式
        chrome_options.add_experimental_option("useAutomationExtension", False)
        # 禁止图片加载
        prefs = {"profile.managed_default_content_settings.images": 2}
        chrome_options.add_experimental_option("prefs", prefs)
        # 设置中文
        chrome_options.add_argument('lang=zh_CN.UTF-8')
        # 更换头部
        chrome_options.add_argument(
            'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')
        # 隐藏浏览器
        chrome_options.add_argument('--headless')  # 隐藏浏览器
        # 部署项目在linux时，其驱动会要求这个参数
        chrome_options.add_argument('--no-sandbox')
        # 创建浏览器对象
        driver = webdriver.Chrome(f, options=chrome_options)
        # 设置执行js代码转换模式
        driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
        })
        # 打开网站 测试
        # driver.get('https://www.baidu.com/')
        return driver

    def getCookie(self):
        # 机器识别滑块验证并自动登录
        driver = self.InitialBrowser()
        mouse = c1()
        url = 'https://passport.tujia.com/PortalSite/LoginPage/?originUrl=https%3A%2F%2Fwww.tujia.com%2F'
        driver.get(url)
        driver.maximize_window()
        wait = WebDriverWait(driver, 10)
        driver.get(url)
        time.sleep(3)
        driver.refresh()
        # 滑动次数超过10次自动失败
        click = 0
        while True:
            # pyautogui.press('f5')
            # keyboard.press(Key.f5)
            # driver.refresh()
            time.sleep(2)
            # mouse.position = (980, 550)
            mouse.position = (680, 550)
            time.sleep(1)
            mouse.press(Button.left)
            mouse.move(400, 2)
            time.sleep(1)
            mouse.release(Button.left)
            time.sleep(2)
            WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME, 'nc-lang-cnt')))
            click += 1
            if click > 10 or driver.find_element_by_class_name('nc-lang-cnt').text == '验证通过':
                break

        time.sleep(2)
        element = driver.find_elements_by_tag_name("div>input")
        key = 0
        for i in element:
            if key == 0:
                time.sleep(1)
                i.send_keys(18510781868)
            if key == 1:
                time.sleep(1)
                i.send_keys("wc121369")
            key += 1

        submit_button = driver.find_element_by_class_name("submit")
        submit_button.click()
        return driver

    def getRoomList(self):
        url = "https://guanjia.tujia.com/feapi/merchantcrm/merchant-web/v2/pc/house/pageHouseInfo"
        self.getCookie().get(url)

    def saveCookie(self):
        url = "https://www.baidu.com"
        driver = self.InitialBrowser()
        driver.get(url)
        time.sleep(1)
        cookies = driver.get_cookies()
        with open("../tmp_file/cookies06.txt", "w") as fp:
            json.dump(cookies, fp)


if __name__ == "__main__":
    t = vcg_get_cookies()
    t.saveCookie()
